#include <iostream>
#include <vector>
#include <map>
#include <string>
using namespace std;

int father[50001];
int osci[50001];

int find(int x)
{
	return father[x] == x ? x : father[x] = find(father[x]);
}

void merge(int s, int p)
{
	int fs = find(s);
	int fp = find(p);
	if (fs != fp) {
		father[fs] = fp;
		osci[fp] = p;
	}
}

int main()
{
	string name, parent;
	map<string, int> idx;
        map<int, string> id;
        for(int i = 0; i < 50001; i++){
                father[i] = i;
        }
	for (;;) {
		cin >> name;
		if (name == "$") {
			return 0;
		}

		if (name[0] == '#') {
			parent = name.substr(1);
			if (idx[parent] == 0) {
				idx[parent] = idx.size() + 1;
                                id[idx[parent]] = parent;
			}
			continue;
		}
                
                if(name[0] == '?'){
                        name = name.substr(1);
                        cout<<name << " " << id[find(idx[name])]<<endl;
                        continue;
                }

		name = name.substr(1);
		if (idx[name] == 0) {
			idx[name] = idx.size() + 1;
                        id[idx[name]] = name;
		}

		merge(idx[name], idx[parent]);
	}
}